package m202402.d26;

import java.util.LinkedList;
import java.util.List;

/**
 * @author: 爱做梦的锤子
 * @date: 2024/2/26 07:54
 */
//230. 二叉搜索树中第K小的元素
public class Q230 {
    public int kthSmallest(TreeNode root, int k) {
        LinkedList<Integer> list = new LinkedList<>();
        travel(root, list, k);
        return list.getLast();
    }

    public void travel(TreeNode node, List<Integer> list, int k) {
        if (node == null) {
            return;
        }
        travel(node.left, list, k);
        if (list.size() >= k) {
            return;
        }
        list.add(node.val);
        if (list.size() >= k) {
            return;
        }
        travel(node.right, list, k);
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
